package com.talent.web.mqtt;

import com.talent.web.mqtt.handler.ReceiveMessageHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.integration.annotation.ServiceActivator;
import org.springframework.integration.channel.DirectChannel;
import org.springframework.integration.core.MessageProducer;
import org.springframework.integration.mqtt.core.MqttPahoClientFactory;
import org.springframework.integration.mqtt.inbound.MqttPahoMessageDrivenChannelAdapter;
import org.springframework.integration.mqtt.support.DefaultPahoMessageConverter;
import org.springframework.messaging.MessageChannel;
import org.springframework.messaging.MessageHandler;

/**
 * @Author: hszhou
 * @Date: 2025/1/8 21:02
 * @Description: 必须描述类做什么事情, 实现什么功能
 */
@Configuration
public class MqttInboundConfiguration {

    //消息通道

    @Autowired
    private MqttConfigurationProperties mqttConfigurationProperties;


    @Autowired
    private MqttPahoClientFactory mqttClientFactory;

    @Autowired
    private ReceiveMessageHandler receiveMessageHandler;

    @Bean
    public MessageChannel intPutChannel(){
        return new DirectChannel();
    }

    //配置入栈是配置 设置订阅的主题以及指定消息的相关熟悉
    @Bean
    public MessageProducer messageProducer(){

        MqttPahoMessageDrivenChannelAdapter mqttPahoMessageDrivenChannelAdapter = new MqttPahoMessageDrivenChannelAdapter(
                mqttConfigurationProperties.getUrl(),
                mqttConfigurationProperties.getSubClientId(),
                mqttClientFactory,
                mqttConfigurationProperties.getSubTopic().split(",")
        );
        mqttPahoMessageDrivenChannelAdapter.setQos(1);
        mqttPahoMessageDrivenChannelAdapter.setConverter(new DefaultPahoMessageConverter());
        mqttPahoMessageDrivenChannelAdapter.setOutputChannel(intPutChannel());

        return mqttPahoMessageDrivenChannelAdapter;
    }

    @Bean
    @ServiceActivator(inputChannel ="intPutChannel")
    public MessageHandler messageInPutHandler(){
        return receiveMessageHandler;
    }
}
